package com.kingmed.kmss.gateway.filter;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.router.SaRouter;
import com.kingmed.kmss.common.constant.sys.CacheConstants;
import com.kingmed.kmss.common.constant.common.OperatorConstants;
import com.kingmed.kmss.common.service.sys.RedisService;
import com.kingmed.kmss.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 对外系统开放相关接口权限校验
 */
@Slf4j
@Component
public class OpenUrlAuthFilter extends SaRouter {


    @Resource
    private RedisService redisService;

    /**
     * 对外提供的开放组
     */
    private final String APP_ID = "appId";

    /**
     * 对外提供的开放组token
     */
    private final String APP_KEY = "appKey";


    private final String COMMON_ERROR_MSG = "接口不存在或暂未授权，请联系CRM管理员！";

    /**
     * 检查是否是调用对外接口
     */
    public boolean check() {

        SaRequest request = SaHolder.getRequest();

        String appId = request.getHeader(APP_ID);
        String appKey = request.getHeader(APP_KEY);
        // 访问的接口是否存在开放接口内
        String requestUrl = request.getRequestPath();
        log.info(" === open url check, appId={}, token={}, requestUrl={}", appId, appKey, requestUrl);
        if (StringUtils.isAnyBlank(appId, appKey)) {
            return false;
        }

        // 获取对外授权列表
        Object cache = redisService.hGet(CacheConstants.OPEN_URL_KEY, appKey);
        if (Objects.isNull(cache)) {
            log.info(" 未知授权令牌");
            return false;
        }
        HashMap<String, String> map = null;
        if (cache instanceof Map) {
            map = (HashMap<String, String>) cache;
        }
        if (Objects.isNull(map) || Objects.isNull(map.get(appId))) {
            throw new SaTokenException(COMMON_ERROR_MSG);
        }
        // 授权访问资源匹配
        String url = map.get(appId);
        if (StringUtils.isBlank(url)){
            throw new SaTokenException(COMMON_ERROR_MSG);
        }
        List<String> urls = Arrays.stream(url.split(OperatorConstants.DH_KEY)).collect(Collectors.toList());
        if (!isMatch(urls, requestUrl)){
            throw new SaTokenException(COMMON_ERROR_MSG);
        }
        return true;
    }

}
